package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.WebCircleFriendsMapper;
import com.eco.fanliapp.entity.WebCircleFriends;
import com.eco.fanliapp.service.FindItemIdUtils;
import com.eco.fanliapp.service.ITaoBaoService;
import com.eco.fanliapp.service.IWebCircleFriendsService;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.Convert;
import com.eco.fanliapp.utils.EmojiUtil;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 朋友圈 服务层实现
 * 
 * @author xiaoxx
 * @date 2019-05-05
 */
@Service
public class WebCircleFriendsServiceImpl extends ServiceImpl<WebCircleFriendsMapper, WebCircleFriends> implements IWebCircleFriendsService {
	@Autowired
	private WebCircleFriendsMapper webCircleFriendsMapper;

	@Autowired
	private FindItemIdUtils findItemIdUtils;

//	@Autowired
//	private FindItemIdUtils findItemIdUtils;


	@Autowired
	private ITaoBaoService taoBaoService;


	/**
     * 查询朋友圈信息
     * 
     * @param id 朋友圈ID
     * @return 朋友圈信息
     */
    @Override
	public WebCircleFriends selectWebCircleFriendsById(Long id)
	{
	    return webCircleFriendsMapper.selectWebCircleFriendsById(id);
	}
	
	/**
     * 查询朋友圈列表
     * 
     * @param currentPage 朋友圈信息
     * @return 朋友圈集合
     */
	@Override
    public ServerResponse<PageInfo> selectWebCircleFriendsList(Integer companyId, Integer currentPage, Integer pageSize)
	{
		PageHelper.startPage(currentPage, pageSize);
        WebCircleFriends friends = new WebCircleFriends();friends.setCompanyId(companyId);
        List<WebCircleFriends> circleFriends = webCircleFriendsMapper.selectWebCircleFriendsList(friends);
        for(WebCircleFriends webCircleFriend: circleFriends){
			webCircleFriend.setFriendName(EmojiUtil.resolveToEmojiFromByte(webCircleFriend.getFriendName()));
			webCircleFriend.setComments(EmojiUtil.resolveToEmojiFromByte(webCircleFriend.getComments()));
			webCircleFriend.setTitle(EmojiUtil.resolveToEmojiFromByte(webCircleFriend.getTitle()));
		}
		if (circleFriends != null){
			return ServerResponse.createBySuccess("查询成功",new PageInfo(circleFriends));
		}
		return ServerResponse.createByErrorMessage("查询失败") ;
	}
	

	@Override
	public ServerResponse insertWebCircleFriends(WebCircleFriends webCircleFriends)
	{
		int circleFriendNum = webCircleFriendsMapper.insertWebCircleFriends(webCircleFriends);
		if(circleFriendNum == 1){
			List<WebCircleFriends> circleFriends = webCircleFriendsMapper.selectWebCircleFriendsList(null);
			return ServerResponse.createBySuccessMessage("增加成功");
		}
		return ServerResponse.createByErrorMessage("增加失败") ;
	}
	
	/**
     * 修改朋友圈
     *
     */
	@Override
	public ServerResponse updateWebCircleFriends(WebCircleFriends webCircleFriends){
		webCircleFriends.setUserName(ApiEnum.PYQ_NAME);
		webCircleFriends.setUserIconUrl(ApiEnum.PYQ_ICON);
		webCircleFriends.setItemMainImageUrl(webCircleFriends.getItemImageUrls().get(0));
		int circleFriendNum;
		Long tableId = webCircleFriends.getTableId();
		String itemid = webCircleFriends.getItemid().trim();//商品id
		ServerResponse<TbkPrivilegeGetInfo.TbkPrivilege> response = taoBaoService.getPrivilegeItemId(Long.valueOf(itemid), null,null);
		TbkPrivilegeGetInfo.TbkPrivilege tbkPrivilege = null;
		if (response != null && response.getData() != null) {
			tbkPrivilege = response.getData();
		} else {
			return ServerResponse.createByErrorMessage("该商品不存在");
		}
//        if(findItemIdUtils.getPrivilegeItemId(Long.valueOf(itemid)) == null){
//            return ServerResponse.createByErrorMessage("该商品不存在");
//        }
//        String maxCommissionRate = findItemIdUtils.getPrivilegeItemId(Long.valueOf(itemid)).getMaxCommissionRate();//佣金比例
//		String couponInfo = findItemIdUtils.getPrivilegeItemId(Long.valueOf(itemid)).getCouponInfo();//优惠券金额

		String maxCommissionRate = tbkPrivilege.getMaxCommissionRate();//佣金比例
		String couponInfo = tbkPrivilege.getCouponInfo();//优惠券金额

		WebCircleFriends circleFriends = webCircleFriendsMapper.selectWebCircleFriendsByitemid(Long.valueOf(itemid));
		if(circleFriends == null){
			//如果不存在查好单库
			HaoDanKuItemInfo info = findItemIdUtils.getHaoDanKuItemId(itemid);
			if(info != null && info.getCode() == 1 && info.getData() != null){
				webCircleFriends.setTitle(info.getData().getItemtitle());
				webCircleFriends.setUpdateTime(System.currentTimeMillis());
				//webCircleFriends.setItemMainImageUrl(info.getData().getItempic());
				webCircleFriends.setCreateTime(System.currentTimeMillis());

//				double price = Double.valueOf(info.getData().getItemendprice()) * Double.valueOf(maxCommissionRate)/100;//得到分享赚的金额
				double price = BigDecimalUtils.Format(new BigDecimal(info.getData().getItemendprice()).multiply(new BigDecimal(maxCommissionRate)).divide(new BigDecimal(100))).doubleValue() ;//得到分享赚的金额

				webCircleFriends.setShareMoney(BigDecimal.valueOf(price));
				int i =webCircleFriendsMapper.insertWebCircleFriends(webCircleFriends);
				if(i > 0) {
					return ServerResponse.createBySuccessMessage("保存成功");
				}else {
					return ServerResponse.createByErrorMessage("保存失败");
				}
			}else {
				//查询淘宝详情
				List<TbkItemInfoGetInfo.NTbkItem> items = findItemIdUtils.getTaoBaoItemId(itemid);
				if(items != null && items.size() > 0) {
					for (TbkItemInfoGetInfo.NTbkItem nTbkItem : items) {
						webCircleFriends.setTitle(nTbkItem.getTitle());
						webCircleFriends.setUpdateTime(System.currentTimeMillis());
						//webCircleFriends.setItemMainImageUrl(nTbkItem.getPictUrl());
						webCircleFriends.setCreateTime(System.currentTimeMillis());
						BigDecimal itemendprice = BigDecimalUtils.Format(
								new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
										.subtract(new BigDecimal(couponInfo))
						);
//						double price = (Double.valueOf(nTbkItem.getZkFinalPrice()) - Double.valueOf(couponInfo)) * Double.valueOf(maxCommissionRate)/100;
						double price = BigDecimalUtils.Format(itemendprice.multiply(new BigDecimal(couponInfo)).divide(new BigDecimal(100))).doubleValue();
						webCircleFriends.setShareMoney(BigDecimalUtils.Format(price));
						int i =webCircleFriendsMapper.insertWebCircleFriends(webCircleFriends);
						if(i > 0) {
							return ServerResponse.createBySuccessMessage("保存成功");
						}else {
							return ServerResponse.createByErrorMessage("保存失败");
						}
					}
				}else {
					return ServerResponse.createByErrorMessage("没有该商品");
				}
			}
		}else {
			circleFriendNum = webCircleFriendsMapper.updateWebCircleFriends(webCircleFriends);
			if (circleFriendNum > 0) {
				return ServerResponse.createBySuccess("保存成功");
			} else {
				return ServerResponse.createByErrorMessage("该商品已存在");
			}
		}
		return ServerResponse.createByErrorMessage("保存失败");
	}



	/**
     * 删除朋友圈对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWebCircleFriendsByIds(String ids)
	{
		return webCircleFriendsMapper.deleteWebCircleFriendsByIds(Convert.toStrArray(ids));
	}

	@Override
	public List<WebCircleFriends> selectWebCircleFriendsLists(WebCircleFriends webCircleFriends) {
		// TODO Auto-generated method stub
		return webCircleFriendsMapper.selectWebCircleFriendsLists(webCircleFriends);
	}

	@Override
	public int updateWebCircleFriendsCount(WebCircleFriends webCircleFriends) {
		// TODO Auto-generated method stub
		webCircleFriends.setUpdateTime(System.currentTimeMillis());
		return webCircleFriendsMapper.updateWebCircleFriendsCount(webCircleFriends);
	}

    @Override
    public List<WebCircleFriends> selectWebCircleFriendsListsLIMIT(Integer start, Integer back, Integer companyId) {
        // TODO Auto-generated method selectWebCircleFriendsListsLIMIT
        start = start == null?0:start;
        back = back == null?20:back;
        return webCircleFriendsMapper.selectWebCircleFriendsListsLIMIT(start,back,companyId);
    }

	@Override
	public ServerResponse delete(Integer id) {
		int delete = webCircleFriendsMapper.delete(Long.valueOf(id));
		if(delete > 0 ){
		   return 	ServerResponse.createBySuccess("删除成功");
		}
		return ServerResponse.createByErrorMessage("删除失败");
	}

	@Override
	public ServerResponse updateStatus(WebCircleFriends webCircleFriends) {
		int i = webCircleFriendsMapper.updateStatus(webCircleFriends);
		if(i > 0){
			return  ServerResponse.createBySuccess();
		}
		return ServerResponse.createByError();
	}

	@Override
	public WebCircleFriends selectByGoodsId(Long numIid) {
		// TODO Auto-generated method stub
		return webCircleFriendsMapper.selectByGoodsIds(numIid);
	}

	@Override
	public WebCircleFriends selectWebCircleFriendsByitemid(Long itemId) {
		// TODO Auto-generated method stub
		return webCircleFriendsMapper.selectWebCircleFriendsByitemid(itemId);
	}

	/**
	 * 查询朋友圈列表
	 *
	 * @return 朋友圈集合
	 */
	@Override
	public List<WebCircleFriends> selectWebCircleFriendsListAll()
	{
		return webCircleFriendsMapper.selectWebCircleFriendsListAll();
	}

}
